import axios from 'axios';
import type { AxiosInstance } from 'axios';

// export enum StatusCode {
//   SUCCESS_CODE = 200
// }

const httplib: AxiosInstance = axios.create({
  baseURL: '',
  responseType: 'json',
});

export function parseResetParaams(url: string, params: AnyObject) {
  return url.replace(/\{[\w]+\}/g, $1 => {
    return params[$1];
  });
}

function get(
    url: string,
    resetParams: AnyObject,
    params: AnyObject,
    headers?: AnyObject,
): any {
  url = parseResetParaams(url, resetParams);
  httplib.get(url, {
    params,
    headers,
  }).then(res => {
    if (res.status === 200) {
      return res.data;
    }
    return res;
  }).catch(err => {
    console.error(err);
    throw err;
  });
}

function post(
    url: string,
    resetParams: AnyObject,
    params: AnyObject,
    headers?: AnyObject,
): any {
  url = parseResetParaams(url, resetParams);
  httplib.post(url, {
    data: params,
    headers,
  }).then(res => {
    if (res.status === 200) {
      return res.data;
    }
  }).catch(err => {
    console.error(err);
  }); ;
}

export default {
  get,
  post,
} as AnyObject;
